<template>
  <div>
    <div class="w-full h-full flex items-center justify-center" @click="openUpload">
      <slot></slot>
    </div>
    <el-dialog
      title="图片上传"
      v-model="state.uploadVisible"
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      align-center
      width="600px"
    >
      <el-tabs v-model="state.tabActive" class="upload-tabs" type="card">
        <el-tab-pane label="本地图片" :name="0">
          <div class="p-[15px]" v-loading="state.loading">
            <el-upload
              ref="uploadRef"
              drag
              action="#"
              accept="image/jpeg,image/png,image/jpg"
              :show-file-list="false"
              :multiple="false"
              :limit="1"
              :http-request="UploadImage"
              :before-upload="beforePicUpload"
            >
              <div class="w-full flex flex-col items-center" v-if="!state.imageUrl">
                <div>
                  <img class="w-[228px]" src="@/assets/images/upload-img.png" alt="" />
                </div>
                <div class="el-upload__text">
                  点击添加图片，仅支持200k以内jpg，jpeg，png格式图片上传
                </div>
              </div>
              <div
                class="flex justify-center items-center cursor-pointer relative"
                @click.stop=""
                v-else
              >
                <div class="w-[160px] h-[160px] relative">
                  <el-image
                    fit="cover"
                    class="h-[160px] w-[160px]"
                    :src="netPath(state.imageUrl)"
                    :preview-src-list="[netPath(state.imageUrl)]"
                  >
                  </el-image>
                  <div class="absolute right-0 top-0 w-[20px] h-[20px] bg-[#000000aa] rounded-full">
                    <el-icon class="!text-[20px] !text-[#fff]" @click.stop="clearUpload">
                      <CircleCloseFilled />
                    </el-icon>
                  </div>
                </div>
              </div>
            </el-upload>
          </div>
        </el-tab-pane>
        <el-tab-pane label="网络图片" :name="1">
          <div class="h-[232px] p-[15px]">
            <div class="my-[10px]">请输入网络地址</div>
            <el-input v-model="state.netUrl" placeholder="https://..."></el-input>
            <div class="text-[#aaa] py-[10px]">
              <p>网络地址头像受第三方地址影响，可能部分场景无法访问。</p>
              <p>建议下载图片到本地，然后使用本地文件上传头像。</p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="closeUpload">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { message } from "@/utils/message";
import { netPath } from "@/utils/common";
import { reqUploadImg } from "@/api/user";
import type { ElUpload } from "element-plus";

const state = reactive({
  tabs: ["本地图片", "网络图片"],
  tabActive: 0,
  previewVisible: false,
  previewPath: "",
  uploadVisible: false,
  loading: false,
  imageUrl: "",
  netUrl: ""
});
const emit = defineEmits(["update"]);
const uploadRef = ref<InstanceType<typeof ElUpload> | null>(null);
const openUpload = () => {
  state.tabActive = 0;
  state.uploadVisible = true;
};

const UploadImage = async (e: any) => {
  try {
    state.loading = true;
    let params = new FormData();
    params.append("ImgPath", e.file);
    let res = await reqUploadImg(params);
    state.loading = false;
    state.imageUrl = "/" + res.data.ImgPath;
  } catch (error) {
    state.loading = false;
    uploadRef.value?.clearFiles();
    console.log(error);
  }
};
const clearUpload = () => {
  state.imageUrl = "";
  state.netUrl = "";
  uploadRef.value?.clearFiles();
};

const closeUpload = () => {
  state.uploadVisible = false;
};

const beforePicUpload = (file: any) => {
  const isIMAGE = file.type === "image/jpeg" || "image/jpg" || "image/png";
  const isLt200K = file.size / 1024 < 200;

  if (!isIMAGE) {
    message.warning("上传文件只能是图片格式!");
  }
  if (!isLt200K) {
    message.warning("上传头像图片大小不能超过 200KB!");
  }
  return isIMAGE && isLt200K;
};

const handleSubmit = () => {
  if (state.tabActive === 0) {
    if (!state.imageUrl) {
      message.warning("请上传图片");
      return;
    }
  } else {
    if (!state.netUrl) {
      message.warning("请输入图片地址");
      return;
    }
  }
  state.uploadVisible = false;
  emit("update", state.tabActive === 0 ? state.imageUrl : state.netUrl);
};
</script>
<style scoped lang="scss">
:deep() {
  .upload-tabs {
    .el-tabs__header {
      padding-bottom: 0;
      margin-bottom: 0;
    }
  }
}
.upload-img-box {
  cursor: pointer;
  border-radius: 4px;
  &:hover {
    .upload-img-tools {
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 4px;
      background-color: rgba(0, 0, 0, 0.5);
      .el-icon {
        color: #fff;
        font-size: 20px;
        margin: 0 10px;
      }
    }
  }
}
</style>
